﻿using System;
using System.IO;
using System.Threading;

namespace Core.Framework
{
    public class iToolConfigFileChangeDetect
    {
        /// <summary>
        /// 定时器触发间隔
        /// </summary>
        const int TimeoutMillis = 2000;

        static iToolType iToolType;

        static FileSystemWatcher watcher = new FileSystemWatcher();

        static Timer Timer = null;

        static Action _actionRestart = null;

        static iToolConfigFileChangeDetect()
        {
            //设置定时器的回调函数。此时定时器未启动
            Timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);
        }

        /// <summary>
        /// 初始化监听
        /// </summary>
        /// <param name="StrWarcherPath">需要监听的目录</param>
        /// <param name="FilterType">需要监听的文件类型(筛选器字符串)</param>
        /// <param name="IsEnableRaising">是否启用监听</param>
        /// <param name="IsInclude">是否监听子目录</param>
        static void WatcherStart(string StrWarcherPath, string FilterType, bool IsEnableRaising, bool IsInclude)
        {
            watcher.BeginInit();
            watcher.Filter = FilterType;
            watcher.IncludeSubdirectories = IsInclude;
            watcher.EnableRaisingEvents = IsEnableRaising;
            //watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size;
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
            watcher.Path = StrWarcherPath;
            watcher.Created += new FileSystemEventHandler((sender, e) => Timer.Change(TimeoutMillis, Timeout.Infinite));
            watcher.Changed += (sender, e) => Timer.Change(TimeoutMillis, Timeout.Infinite);
            watcher.Deleted += (sender, e) => Timer.Change(TimeoutMillis, Timeout.Infinite);
            watcher.Renamed += (sender, e) => Timer.Change(TimeoutMillis, Timeout.Infinite);
            watcher.EndInit();
        }

        public static void StartAndRegisterChangeEvent(Action action, iToolType _iToolType = iToolType.Service)
        {
            iToolType = _iToolType;
#if DEBUG
            WatcherStart($"D:/iTool-Cloud-Framework", "*.iToolConfig", true, false);
            // Directory.GetCurrentDirectory();
#else
            WatcherStart("/var/iTool", "*.iToolConfig", true, false);
#endif
            _actionRestart = action;
        }

        public static void Stop()
        {
            watcher.EnableRaisingEvents = false;
        }

        private static void OnWatchedFileChange(object state)
        {
            if (AppSetting.ReSetiToolConfigure(iToolType))
            {
                _actionRestart?.Invoke();
            }
        }
    }

    public enum iToolType
    {
        None,
        Connector,
        Service
    }
}


